package pkg

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"net/url"
)

const (
	appID     = "wx91836807fae0f67e"
	appSecret = "d7aaf8ba01ca017b659b77c85dd4aa35"
)

func WechatLoginCallback(w http.ResponseWriter, r *http.Request) {
	// 获取微信回调的 code
	code := r.URL.Query().Get("code")
	if code == "" {
		http.Error(w, "缺少 code 参数", http.StatusBadRequest)
		return
	}

	// 通过 code 获取 access_token
	accessToken, openID, err := getWeChatAccessToken(code)
	if err != nil {
		http.Error(w, fmt.Sprintf("获取 access_token 失败: %v", err), http.StatusInternalServerError)
		return
	}

	// 通过 access_token 和 openID 获取用户信息
	userInfo, err := getWeChatUserInfo(accessToken, openID)
	if err != nil {
		http.Error(w, fmt.Sprintf("获取用户信息失败: %v", err), http.StatusInternalServerError)
		return
	}
	fmt.Println()
	// 返回用户信息给前端
	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(userInfo)
}

func getWeChatAccessToken(code string) (string, string, error) {
	apiURL := "https://api.weixin.qq.com/sns/oauth2/access_token"
	params := url.Values{}
	params.Set("appid", appID)
	params.Set("secret", appSecret)
	params.Set("code", code)
	params.Set("grant_type", "authorization_code")

	resp, err := http.Get(apiURL + "?" + params.Encode())
	if err != nil {
		return "", "", fmt.Errorf("请求微信 API 失败: %v", err)
	}
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return "", "", fmt.Errorf("读取响应失败: %v", err)
	}

	var result struct {
		AccessToken string `json:"access_token"`
		OpenID      string `json:"openid"`
		ErrCode     int    `json:"errcode"`
		ErrMsg      string `json:"errmsg"`
	}
	if err := json.Unmarshal(body, &result); err != nil {
		return "", "", fmt.Errorf("解析响应失败: %v", err)
	}

	if result.ErrCode != 0 {
		return "", "", fmt.Errorf("微信返回错误: %s", result.ErrMsg)
	}

	return result.AccessToken, result.OpenID, nil
}

func getWeChatUserInfo(accessToken, openID string) (map[string]interface{}, error) {
	apiURL := "https://api.weixin.qq.com/sns/userinfo"
	params := url.Values{}
	params.Set("access_token", accessToken)
	params.Set("openid", openID)
	params.Set("lang", "zh_CN")

	resp, err := http.Get(apiURL + "?" + params.Encode())
	if err != nil {
		return nil, fmt.Errorf("请求微信 API 失败: %v", err)
	}
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, fmt.Errorf("读取响应失败: %v", err)
	}

	var userInfo map[string]interface{}
	if err := json.Unmarshal(body, &userInfo); err != nil {
		return nil, fmt.Errorf("解析用户信息失败: %v", err)
	}

	if errcode, ok := userInfo["errcode"]; ok {
		fmt.Println("信息>>>", errcode)
		return nil, fmt.Errorf("微信返回错误: %v", userInfo["errmsg"])
	}

	return userInfo, nil
}
